package com.hmall.trade.listenr;

import com.hmall.api.client.PayClient;
import com.hmall.api.dto.PayOrderDTO;
import com.hmall.trade.constants.MqConstants;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class OrderDelayMessageListen {
    private final IOrderService orderService;
    private final PayClient payClient;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.DELAYQUEUE)
            ,exchange = @Exchange(name = MqConstants.DELAYEXCHANGE,delayed="true")
            ,key = MqConstants.DELAYROUTINGKEY
    ))
    public void listenOrderDelay(Long orderId){
        //1.查询订单
        Order order = orderService.getById(orderId);
        //2.检测订单状态,判断是否已支付
        if(order==null||order.getStatus()!=1){
            //订单不存在或者已支付
            return;
        }
        //3.未支付，需要查询支付流水状态
        PayOrderDTO payOrderDTO = payClient.queryPayOrderByBizOrderNo(orderId);

        //4.判断是否已支付
        if(payOrderDTO!=null||payOrderDTO.getStatus()==3){
            //4.1已支付，标记订单状态为已支付
            orderService.markOrderPaySuccess(orderId);
            return;
        }else {
            orderService.cancelOrder(orderId);
            //4.2 未支付，标记订单状态为已取消,恢复库存
        }



    }
}
